package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 鹏少
 * @Date 2023/9/24
 * @Date 10:53
 */
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        List<LocalDate> localDateList = new ArrayList<>();
        LocalDate currentTime = begin;
        while (!currentTime.equals(end)) {
            localDateList.add(currentTime);
            currentTime = currentTime.plusDays(1);

        }
        localDateList.add(end);

        String joinString = StringUtils.join(localDateList, ",");
        turnoverReportVO.setDateList(joinString);

        List<Double> priceList = new ArrayList<>();
        Integer status = Orders.COMPLETED;
        for (LocalDate localDate : localDateList) {
            LocalDateTime startTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Double getDayTotal = orderMapper.getTurnoverSum(status, startTime, endTime);
            getDayTotal = getDayTotal == null ? 0.0 : getDayTotal;
            priceList.add(getDayTotal);

        }
        String joinPrice = StringUtils.join(priceList, ",");
        turnoverReportVO.setTurnoverList(joinPrice);
        return turnoverReportVO;


    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {


        UserReportVO userReportVO = new UserReportVO();
        List<LocalDate> localDateList = new ArrayList<>();
        LocalDate currentTime = begin;
        while (!currentTime.equals(end)) {
            localDateList.add(currentTime);
            currentTime = currentTime.plusDays(1);

        }
        localDateList.add(end);
        String joinString = StringUtils.join(localDateList, ",");


        List<Integer> newUsers = new ArrayList<>();
        List<Integer> totalUsers = new ArrayList<>();

        for (LocalDate localDate : localDateList) {
            LocalDateTime startTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap();
            map.put("beginTime", startTime);
            map.put("endTime", endTime);
            Map map1 = new HashMap();
            map1.put("endTime", endTime);

            Integer newUser = userMapper.getUsers(map);
            Integer totalUser = userMapper.getUsers(map1);
            newUsers.add(newUser);
            totalUsers.add(totalUser);

        }

        String newUserStr = StringUtils.join(newUsers, ",");
        String totalUserStr = StringUtils.join(totalUsers, ",");
        userReportVO.setDateList(joinString);
        userReportVO.setNewUserList(newUserStr);
        userReportVO.setTotalUserList(totalUserStr);


        return userReportVO;
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {


        List<LocalDate> localDateList = new ArrayList<>();
        LocalDate currentTime = begin;
        while (!currentTime.equals(end)) {
            localDateList.add(currentTime);
            currentTime = currentTime.plusDays(1);

        }
        localDateList.add(end);
        String localDateListStr = StringUtils.join(localDateList, ",");


        //有效的
        List<Integer> validOrderCountList = new ArrayList<>();
        List<Integer> orderCountList = new ArrayList<>();
        //总数的
        Integer totalOrderCountSum = 0;
        Integer validOrderCountSum = 0;

        for (LocalDate localDate : localDateList) {

            LocalDateTime startTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Integer status = Orders.COMPLETED;
            Map map = new HashMap();
            map.put("beginTime", startTime);
            map.put("endTime", endTime);
            map.put("status", status);
            Integer validOrderCount = orderMapper.getOrdersStatistics(map);
            validOrderCountList.add(validOrderCount);
            validOrderCountSum += validOrderCount;

            Map map1 = new HashMap();
            map1.put("beginTime", startTime);
            map1.put("endTime", endTime);
            Integer orderCount = orderMapper.getOrdersStatistics(map1);
            orderCountList.add(orderCount);
            totalOrderCountSum += orderCount;


        }
        String validOrderCountListStr = StringUtils.join(validOrderCountList, ",");
        String orderCountListStr = StringUtils.join(orderCountList, ",");


        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(localDateListStr);
        orderReportVO.setOrderCountList(orderCountListStr);
        orderReportVO.setValidOrderCountList(validOrderCountListStr);
        orderReportVO.setValidOrderCount(validOrderCountSum);
        orderReportVO.setTotalOrderCount(totalOrderCountSum);
        Double orderCompletionRate = 0.0;

        if (totalOrderCountSum != 0) {
            orderCompletionRate = validOrderCountSum.doubleValue() / totalOrderCountSum;

        }


        orderReportVO.setOrderCompletionRate(orderCompletionRate);
        return orderReportVO;
    }

    @Override
    public SalesTop10ReportVO selectTopTen(LocalDate begin, LocalDate end) {

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTOS = orderMapper.selectTopTen(beginTime, endTime);
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        if (goodsSalesDTOS != null && goodsSalesDTOS.size() > 0) {
            for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOS) {
                nameList.add(goodsSalesDTO.getName());
                numberList.add(goodsSalesDTO.getNumber());

            }
        }


        String nameListStr = StringUtils.join(nameList, ",");
        String numberListStr = StringUtils.join(numberList, ",");


        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(nameListStr);
        salesTop10ReportVO.setNumberList(numberListStr);
        return salesTop10ReportVO;


    }

    @Override
    public void export(HttpServletResponse response)  {

        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");


        try {
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = excel.getSheetAt(0);
            LocalDate begin=LocalDate.now().minusDays(30);
            LocalDate end=LocalDate.now().minusDays(1);
            sheet.getRow(1).getCell(1).setCellValue(begin+"至"+end);
            BusinessDataVO thirtyData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(thirtyData.getTurnover());
            row.getCell(4).setCellValue(thirtyData.getOrderCompletionRate());
            row.getCell(6).setCellValue(thirtyData.getNewUsers());


            sheet.getRow(4).getCell(2).setCellValue(thirtyData.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(thirtyData.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                LocalDate date=begin.plusDays(i);
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                XSSFRow sheetRow = sheet.getRow(7 + i);
                sheetRow.getCell(1).setCellValue(date.toString());
                sheetRow.getCell(2).setCellValue(businessData.getTurnover());
                sheetRow.getCell(3).setCellValue(businessData.getValidOrderCount());
                sheetRow.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                sheetRow.getCell(5).setCellValue(businessData.getUnitPrice());
                sheetRow.getCell(6).setCellValue(businessData.getNewUsers());


            }


            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            outputStream.flush();
            outputStream.close();
            excel.close();


        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
